import {getInfo, getRouters} from "@/api/system/user";
import {removeToken, setToken} from "@/utils/auth";
import {login, logout} from "@/api/auth";
import router, {commonRoutes, constantRoutes} from "@/router";
import Layout from "@/layout/AppMain";
import ParentView from "@/components/ParentView";
import InnerLink from "@/components/InnerLink";

const user = {
    state: {
        id: '',
        token: '',
        username: '',
        nickname: '',
        avatar: '',
        roles: [],
        permissions: [],
        sidebarRouters: []
    },
    mutations: {
        SET_ID: (state, id) => {
            state.id = id
        },
        SET_USERNAME: (state, username) => {
            state.username = username
        },
        SET_NICKNAME: (state, nickname) => {
            state.nickname = nickname
        },
        SET_AVATAR: (state, avatar) => {
            state.avatar = avatar
        },
        SET_TOKEN: (state, token) => {
            state.token = token
        },
        SET_ROLES: (state, roles) => {
            state.roles = roles
        },
        SET_PERMISSIONS: (state, permissions) => {
            state.permissions = permissions
        },
        SET_SIDEBAR_ROUTERS: (state, routes) => {
            state.sidebarRouters = routes
        },
    },
    actions: {
        // 登录
        Login({commit}, userInfo) {
            return new Promise((resolve, reject) => {
                login(userInfo).then(res => {
                    setToken(res.token)
                    commit('SET_TOKEN', res.token)
                    resolve()
                }).catch(error => {
                    reject(error)
                })
            })
        },
        // 获取用户信息
        GetInfo({commit, state}) {
            return new Promise((resolve, reject) => {
                getInfo().then(res => {
                    const user = res.user
                    const avatar = (user.avatar === "" || user.avatar == null) ? require("@/assets/imgs/avatar.jpg") : process.env.BASE_URL + user.avatar;
                    if (res.roles && res.roles.length > 0) { // 验证返回的roles是否是一个非空数组
                        commit('SET_ROLES', res.roles)
                        commit('SET_PERMISSIONS', res.permissions)
                    } else {
                        commit('SET_ROLES', ['ROLE_DEFAULT'])
                    }
                    commit('SET_ID', user.id)
                    commit('SET_USERNAME', user.username)
                    commit('SET_NICKNAME', user.nickname)
                    commit('SET_AVATAR', avatar)
                    resolve(res)
                }).catch(error => {
                    //reject("获取用户信息异常")
                })
            })
        },
        // 退出系统
        LogOut({commit, state}) {
            return new Promise((resolve, reject) => {
                logout(state.token).then(() => {
                    commit('SET_TOKEN', '')
                    commit('SET_ROLES', [])
                    commit('SET_PERMISSIONS', [])
                    removeToken()

                    resolve()
                }).catch(error => {
                    reject(error)
                })
            })
        },
        // 生成路由
        GenerateRoutes({commit}) {
            return new Promise((resolve, reject) => {
                // 向后端请求路由数据
                getRouters().then((res) => {
                    const asyncRouterMap = filterAsyncRouter(res.data);
                    const allRoutes = constantRoutes.concat(asyncRouterMap);

                    // 添加404重定向规则
                    allRoutes.push({ path: '/:pathMatch(.*)*', redirect: '/404', hidden: true });

                    // 动态添加路由
                    allRoutes.forEach(route => {
                        if (!router.hasRoute(route.name)) { // 检查路由是否已存在
                            router.addRoute(route);
                        }
                    });
                    commit('SET_SIDEBAR_ROUTERS', filteredRoutes(allRoutes));
                    resolve(asyncRouterMap);
                }).catch(error => {
                    reject("获取路由信息异常")
                })
            })
        },
    }
}

// 解析后端返回的路由数据
function filterAsyncRouter(asyncRouterMap) {
    return asyncRouterMap.filter(router =>{
        if (router.component){
            if (router.component === 'Layout'){
                router.component = Layout;
            }else if (router.component === 'ParentView'){
                router.component = ParentView;
            }else if (router.component === 'InnerLink') {
                router.component = InnerLink;
            }else {
                router.component = loadView(router.component)
            }
        }
        if (router.children && router.children.length) {
            router.children = filterAsyncRouter(router.children)
        } else {
            delete router['children']
            delete router['redirect']
        }
        return true
    })
}

function filteredRoutes(routerMap){
    const newRoutes = [];

    routerMap.forEach(route => {
        // 忽略隐藏的路由
        if (route.hidden) return;

        // 如果路由需要始终显示
        if (route.alwaysShow) {
            if (route.children && route.children.length === 1) {
                newRoutes.push(...route.children); // 使用扩展运算符添加子路由
            } else {
                newRoutes.push(route);
            }
        } else if (route.children) {
            newRoutes.push(...route.children); // 使用扩展运算符添加子路由
        }
    });
    return newRoutes;
}

// 路由组件的懒加载
function loadView(view) {
    return () => import(`@/views/${view}`);
}

export default user